package handlers

import (
	"awesome-devops/applications/backend/modules/requests"
	"awesome-devops/applications/backend/modules/services"
	"awesome-devops/applications/models"
	"awesome-devops/boot"
	helper2 "awesome-devops/helper"
	"gitee.com/jjawesomejj/awesome-util/helper/timeHelper"
	awesomehttp "gitee.com/jjawesomejj/awesomehttp/system"
	"gitee.com/jjawesomejj/awesomehttp/system/helper"
	"reflect"
	"time"
)

type ServerConfigHandler struct {
	awesomehttp.HttpBaseHandler
}

func (context *ServerConfigHandler) GetModuleName() string {
	return "/server/"
}

func (context *ServerConfigHandler) ActionList() interface{} {
	keyword := context.HttpContext.Get("keyword", "").(string)
	service := services.ServerConfigService{}
	return service.List(keyword, requests.ResolveDefaultPageRequest(context.HttpContext))
}

func (context *ServerConfigHandler) ActionAlive() interface{} {
	serverId := requests.Input(context.HttpContext, "server_id", reflect.Int).(int)
	service := services.ServerConfigService{}
	return service.CheckServerIsAlive(float64(serverId))
}

func (context *ServerConfigHandler) ActionSelectList() interface{} {
	service := services.ServerConfigService{}
	return service.SelectList()
}

func (context *ServerConfigHandler) ActionSave() interface{} {
	service := services.ServerConfigService{}
	projectId := int(requests.Input(context.HttpContext, "project_id", reflect.Float64).(float64))
	name := requests.Input(context.HttpContext, "name", reflect.String).(string)
	needUpload := int(requests.Input(context.HttpContext, "need_upload", reflect.Float64).(float64))
	outPutDir := context.HttpContext.PostOne("output_dir", "").(string)
	uploadDir := ""
	if needUpload == models.NEED_UPLOAD {
		uploadDir = requests.Input(context.HttpContext, "upload_dir", reflect.String).(string)
	}
	serverIds := context.HttpContext.PostOne("server_id_json", make([]int, 0))
	beforeHook := cover(context.HttpContext.PostOne("before_hook").([]interface{}))
	afterHook := cover(context.HttpContext.PostOne("after_hook").([]interface{}))
	files := cover(context.HttpContext.PostOne("files").([]interface{}))
	tx := boot.GetDbConnection().Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			panic(tx)
		}
	}()
	filesList := service.HandleFiles(files)
	beforeHooks, afterHooks := service.HandleHook(beforeHook, afterHook)
	beforeHookIds := helper2.ListMap(beforeHooks, func(index int, item interface{}) interface{} {
		return item.(models.RunStep).ID
	})
	afterHookIds := helper2.ListMap(afterHooks, func(index int, item interface{}) interface{} {
		return item.(models.RunStep).ID
	})
	fileIds := helper2.ListMap(filesList, func(index int, item interface{}) interface{} {
		return item.(models.ProcessFiles).Id
	})
	configId := context.HttpContext.PostOne("id")
	model := models.Process{
		Name:                 name,
		ServerIdJson:         helper.JsonEncode(serverIds),
		NeedUpload:           needUpload,
		BeforeUploadStepJson: helper.JsonEncode(beforeHookIds),
		AfterUploadStepJson:  helper.JsonEncode(afterHookIds),
		UploadExcludeDir:     context.HttpContext.PostOne("upload_exclude_dir").(string),
		ExtParams:            context.HttpContext.PostOne("ext_params", "").(string),
		UploadDir:            uploadDir,
		Files:                helper.JsonEncode(fileIds),
		OutputDir:            outPutDir,
		ProjectId:            uint(projectId),
		CreateTime:           timeHelper.Now(),
		UpdateTime:           timeHelper.Now(),
	}
	if configId != nil {
		model.ID = uint(configId.(float64))
	}
	processId := context.HttpContext.PostOne("id", nil)
	if processId != nil {
		model.ID = uint(processId.(float64))
	}

	boot.GetDbConnection().Save(&model)
	tx.Commit()
	//afterHook:=context.HttpContext.PostOne("afterHook")
	return "success"
}

func (context *ServerConfigHandler) ActionSaveServer() interface{} {
	sshIp := requests.Input(context.HttpContext, "ssh_ip", reflect.String).(string)
	sshPort := requests.Input(context.HttpContext, "ssh_port", reflect.Int).(int)
	sshUser := requests.Input(context.HttpContext, "ssh_user", reflect.String).(string)
	serverName := requests.Input(context.HttpContext, "server_name", reflect.String).(string)
	id := requests.Input(context.HttpContext, "id", reflect.Int, 0).(int)
	serverConfig := models.ServerConfig{
		SshIp:      sshIp,
		SshPort:    sshPort,
		SshUser:    sshUser,
		ServerName: serverName,
	}
	if id != 0 {
		serverConfig.ID = uint(int(id))
	}
	serverConfig.CreateTime = time.Now()
	serverConfig.UpdateTime = time.Now()
	boot.GetDbConnection().Save(&serverConfig)
	return serverConfig.ID

}

func cover(data []interface{}) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	for _, item := range data {
		res = append(res, item.(map[string]interface{}))
	}
	return res
}
